package com.icinfo.cloud.provider.common.crontask;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.utils.PdfUtil;
import com.icinfo.cloud.provider.common.utils.SpringContextUtil;
import com.icinfo.cloud.provider.peripheralinterface.electricinvoice.dto.ElectricInvoiceRequest;
import com.icinfo.cloud.provider.peripheralinterface.electricinvoice.service.IElectricInvoiceInterface;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.RebuildDocumentDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.PaymentElectricInvoiceKeyInfoDto;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.PaymentResultDealDto;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentResultRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentMainRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentResultRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentResultRecordService;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 同步缴款结果
 * @author liyafeng
 * @date 2023/6/29
 */

@Configuration
@EnableScheduling
@Slf4j
@RestController
@RequestMapping("/unifiedPaymentResultTask")
public class UnifiedPaymentResultTask {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private CasePaymentMainRecordMapper casePaymentMainRecordMapper;
    @Resource
    private ICasePaymentResultRecordService casePaymentResultRecordService;
    private static final String SYN_PAYMENT_RESULT_REDIS_KEY = "PUNISH:TASK:SYN_PAYMENT_RESULT_REDIS_KEY";

    /**
     * 描述：同步缴款电子发票
     *
     * @author xiangyuyu
     * @date 2022/10/12
     * @since 1.4.2
     */
    @ApiOperation(value = "同步缴款结果", httpMethod = "POST")
    @PostMapping("/synchronizePaymentResult")
    //@Scheduled(cron = "0 */60 * * * ?")
    public void synchronizePaymentResult() {
        LocalDateTime startTime = LocalDateTime.now();
        log.info("synchronizePaymentResult start-startTime:{}", startTime);
        //防止多台服务器重复执行（过期时间设置为10分钟，预防服务器时间不同步）
        if (!redisTemplate.opsForValue().setIfAbsent(SYN_PAYMENT_RESULT_REDIS_KEY, SYN_PAYMENT_RESULT_REDIS_KEY, 10, TimeUnit.MINUTES)) {
            log.info("--------当前服务器未拿到分布式锁，不执行逻辑----------");
            return;
        }
        //获取状态为待支付的缴款信息
        Example example=new Example(CasePaymentMainRecord.class);
        example.createCriteria().andIsNull("status");
        List<CasePaymentMainRecord> casePaymentMainRecords=casePaymentMainRecordMapper.selectByExample(example);
        List<String> noticeNoList=new ArrayList<>();
        for (CasePaymentMainRecord casePaymentMainRecord:casePaymentMainRecords) {
            noticeNoList.add(casePaymentMainRecord.getNoticeNo());
        }
        if(ObjectUtils.isNotEmpty(noticeNoList)) {
            PaymentResultDealDto dto = new PaymentResultDealDto();
            dto.setNoticeNoList(noticeNoList);
            casePaymentResultRecordService.savePaymentResultAndDealCaseInfo(dto);
        }
        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime, endTime);
        long seconds = duration.getSeconds();
        log.info("synchronizePaymentResult end-endTime:{},consume:{} s", endTime, seconds);
    }


}
